package worker

import (
	"context"
	"math/rand"
	"os/exec"
	"time"

	"gitee.com/taotao_today/crontab/crontab/common"
)

type Executor struct {
}

var G_executor *Executor

func InitExecutor() {
	G_executor = &Executor{}
	return
}

func (e *Executor) ExecutorJob(info *common.JobExecuteInfo) {
	go func() {
		result := &common.JobExecuteResult{
			ExecuteInfo: info,
			Output:      make([]byte, 0),
		}

		// 首先获取分布式锁
		lock := G_jobMgr.CreateJobLock(info.Job.Name)

		// 记录任务开始时间
		result.StartTime = time.Now()

		// 上锁
		// 随机睡眠(0~1s): 让每个协程都有机会调度到任务
		time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)

		err := lock.TryLock()
		defer lock.Unlock()

		if err != nil {
			// 上锁失败
			result.Err = err
			result.EndTime = time.Now()
		} else {
			// 重置任务开始时间
			result.StartTime = time.Now()
			// 执行Shell命令
			cmd := exec.CommandContext(context.TODO(), "C:\\Program Files\\Git\\bin\\bash.exe", "-c", info.Job.Command)

			// 执行并捕获输出
			output, err := cmd.CombinedOutput()

			result.Output = output
			result.Err = err
			// 记录任务结束时间
			result.EndTime = time.Now()
			// 任务执行完成后，把执行结果返回给Scheduler, Scheduler会从executing Table中删除掉执行记录
			G_scheduler.PushJobResult(result)
		}
		// 任务执行完成后，把执行的结果返回给Scheduler，Scheduler会从executingTable中删除掉执行记录
		G_scheduler.PushJobResult(result)

	}()
}
